package com.yc.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Arrays;
import java.util.Scanner;

public class QQClient {

    public static void main(String[] args) throws IOException, InterruptedException {
        // 创建之后立即连接 => 返回 Socket
        Socket socket = new Socket("127.0.0.1", 9999);
        System.out.println("连接成功!");

        InetAddress inetAddress = socket.getInetAddress();
        System.out.println("主机地址 = " + inetAddress.getHostAddress());
        byte[] address = inetAddress.getAddress();
        System.out.println("IP地址 = " + Arrays.toString(address));
        System.out.println("主机名 = " + inetAddress.getHostName());

        // 获取输入输出流
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        // 屏幕输入对象
        Scanner scanner = new Scanner(System.in);

        Thread readThread = new Thread(() -> {
            boolean running = true;
            while (running) {
                try {
                    QQServer.recv(in);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread writeThread = new Thread(() -> {
            boolean running = true;
            while (running) {
                Object data = QQServer.input(scanner);
                try {
                    QQServer.send(data, out);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        readThread.start();
        writeThread.start();

        // 等待读写线程结束, 主线程才执行关闭的代码
        readThread.join();
        writeThread.join();

        // Unreachable statement 代码不可达
        in.close();
        out.close();
        socket.close();
    }
}
